// 16进制转换为整数
export function hex2int(hexValue) {
  return parseInt('0x' + hexValue, 16)
}

// 整数转换为16进制(6位)
export function int2hex(intValue) {
  let hexValue = parseInt(intValue).toString(16)
  const n = hexValue.length
  if (n > 6) {
    return hexValue.slice(0, 6)
  } else if (n === 6) {
    return hexValue
  } else {
    for (let i = 0; i < 6 - n; i++) {
      hexValue = '0' + hexValue
    }
    return hexValue
  }
}

export function bool2int(val) {
  return val ? 1 : 0
}

export function int2bool(val) {
  if (val === null || val === undefined) return false
  return val !== 0
}

export function isValid(obj) {
  return obj !== null && obj !== undefined
}

export function getClass(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1)
}

export function isType(obj, sType) {
  return getClass(obj).toLowerCase() === sType.toLowerCase()
}

export function isFunction(obj) {
  return getClass(obj) === 'Function'
}

export function isObject(obj) {
  return getClass(obj) === 'Object'
}

export function isString(obj) {
  return getClass(obj) === 'String'
}

export function isBoolean(obj) {
  return getClass(obj) === 'Boolean'
}

export function isNumber(obj) {
  return getClass(obj) === 'Number'
}

export function isArray(obj) {
  return getClass(obj) === 'Array'
}

export function isBlob(obj) {
  return getClass(obj) === 'Blob'
}

export function isValidType(obj, type) {
  return obj !== undefined && obj !== null && getClass(obj) === type
}

// 浮点数检测正则表达式
// https://www.cnblogs.com/fubuki/p/9724459.html
// const FloatNumberReg = /^(0|[1-9]\d*|[1-9]\d*\.\d+|0\.\d*[1-9]\d*)$/
const FloatNumberReg = /^[+-]?(0|([1-9]\d*))(\.\d+){1}$/

export function isFloatNumber(obj) {
  const ret = getClass(obj) === 'Number'
  if (!ret) return false
  return FloatNumberReg.test(obj.toString())
}

export function parseJsonObject(str) {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str)
      if (typeof obj === 'object' && obj) {
        return obj
      } else {
        return null
      }
    } catch (e) {
      console.log('[异常]转换json字符串: ' + str + '失败!错误信息:' + e)
      return null
    }
  } else {
    return null
  }
}

// 清空对象
export function clearObject(obj) {
  if (obj === null || obj === undefined || !isObject(obj)) return
  for (const key in obj) {
    // console.log(key)
    delete obj[key]
  }
}

export function DECLARE_CLASS(cls, parent) {
  if (parent != null) {
    cls.prototype = Object.create(parent.prototype)
  }
  cls.prototype.constructor = cls
}
